#!usr/bin/python
#encoding=utf-8

import urllib
import time
import uuid
from datetime import datetime
from wm.lib import monitorlib
from wm.etc.config import ALARMTYPE
from wm.lib.loglib import log_error
from wm.db.TransactionManager import TransactionManager

def website_download_speed(host, count = 1):
    for i in xrange(count):
        try:
            start = datetime.now()
            webpage = urllib.urlopen(str(host))
            end = datetime.now()
        except Exception as e:
            log_error("website_download_speed():"+str(e))
            time.sleep(1) 
            continue  
        downloadtime = (end - start).microseconds /1000000.0
        downloadspeed = len(webpage.read())/1024.0/downloadtime
        return True , downloadspeed
    return False , 0

def download_speed_alarm(row):
    try:
        sql = None
        isalarm,speed = website_download_speed(row[1])
        tran = TransactionManager()
        try:            
            if isalarm == False or speed < row[5]:
                alarmcontent = 'downloadspeed:'+str(float('%.3f'%speed))
                alarmid = uuid.uuid1().__str__().replace("-","") 
                sql = "insert into alarmevent(id,createDate,modifyDate,alertCategory,alertContent,occurrenceDate,"+\
                                    "status,websiteName,websiteConfigInfo_id) "+\
                                    "values('" + alarmid + "'," + " CURRENT_TIMESTAMP()," + " CURRENT_TIMESTAMP()," +\
                                    str(ALARMTYPE['DOWNLOAD_SPEEED_ALARM']) + ",'" + alarmcontent + "'," + "CURRENT_TIMESTAMP()," + str(0) + ",'" + row[2] + "'," +\
                                    "'" + row[0] + "')"
                            
                tran.execute(sql)
                monitorlib.update_recent_alarmevent(tran,row[0],row[2],str(ALARMTYPE['DOWNLOAD_SPEEED_ALARM']),alarmcontent)
                
                sql = "insert into downloadspeed("+\
                                 "id,createDate,modifyDate,downSpeed,isNomal,alarmEvent_id,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 "," + str(float('%.3f'%speed)) + "," + str(0) + ",'"+ str(alarmid) + "','" + row[0] + "')"    
            
            else:
                sql = "insert into downloadspeed("+\
                                 "id,createDate,modifyDate,downSpeed,isNomal,websiteConfigInfo_id) "+\
                                 "values(replace(uuid(),'-','')," + "CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP()" +\
                                 ",'" + str(float('%.3f'%speed)) + "'," + str(1) + ",'" + row[0] + "')" 
            print sql
            tran.execute(sql)
            tran.commitTransaction()
        except:
            print '-----download exception-------------'
            log_error('download exception'+str(sql))
            tran.rollbackTransaction()
        finally:
            tran.close()
    except Exception as e:
        log_error("download_speed_alarm():"+str(e))
        print "download_speed_alarm():",str(e)